﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Views;
using Models;
using System.Data;

namespace Presenters
{
    /// <summary>
    /// Presenter for the Export Results window
    /// </summary>
    public class ExportResultsPresenter : PresenterBase<IExportResultsView>
    {
        /// <summary>
        /// Initialise the ExportResultsPresenter
        /// </summary>
        /// <param name="view">A view that implements IExportResultsView</param>
        /// <param name="dbListToExport">A list of databases that contain canCloseApplication sets</param>
        public ExportResultsPresenter(IExportResultsView view, List<Database> dbListToExport)
            : base(view)
        {
            // Initialise the view
            View.AvailableDatabases = new List<Database>();
            View.ExportStyle = Services.QueryExportStyle.SeperateFiles;
            View.ExportType = Services.QueryExportType.CommaSeperated;

            if (dbListToExport != null)
            {
                // Get a list of databases that actually have canCloseApplication sets we can export (ones that have tables of data)
                List<Database> dbsWithTableResults = (from db in dbListToExport
                                                      where (db.Result != null) && (db.Result.Result != null) && (db.Result.Result is DataTable)
                                                      select db).ToList();

                // Make sure all the canCloseApplication sets are NOT selected for export
                foreach (Database db in dbsWithTableResults)
                {
                    db.Result.SelectedForExport = false;
                }

                View.AvailableDatabases = dbsWithTableResults;
            }
        }

        /// <summary>
        /// Browse for a file to export the data to
        /// </summary>
        public void BrowseForExportFile()
        {
            string fileName = ViewManager.ViewFactory.GetFileToSave("Enter a file name to export the result sets to", "",
                                                  "All Files (*.*)|*.*", "Query Results.txt", View);

            if (!string.IsNullOrEmpty(fileName))
            {
                // The user did not press cancel so update the export file location
                View.ExportFile = fileName;
            }
        }

        /// <summary>
        /// Select all items in the canCloseApplication set list
        /// </summary>
        public void SelectAll()
        {
            foreach (Database db in View.AvailableDatabases)
            {
                db.Result.SelectedForExport = true;
            }
        }

        /// <summary>
        /// Un-select all items in the canCloseApplication set list
        /// </summary>
        public void SelectNone()
        {
            foreach (Database db in View.AvailableDatabases)
            {
                db.Result.SelectedForExport = false;
            }
        }

        /// <summary>
        /// Based on the settings the user has entered, export the selected canCloseApplication sets
        /// </summary>
        /// <returns>True if the export was successful</returns>
        public bool ExportData()
        {
            bool result = false;

            // Validate the export settings
            string validationError = Validate();
            if (!string.IsNullOrEmpty(validationError))
            {
                ViewManager.ViewFactory.DisplayError(validationError, "Export Error");
            }
            else
            {
                // Export the data
                Services.QueryService service = new Services.QueryService();
                string errorMsg;
                List<Database> dbToExport = View.AvailableDatabases.Where(x => x.Result.SelectedForExport).ToList();

                if (dbToExport != null)
                {
                    service.ExportResults(View.ExportFile, dbToExport, View.ExportType, View.ExportStyle, out errorMsg);

                    // Did we receive an error message?
                    if (!string.IsNullOrEmpty(errorMsg))
                    {
                        ViewManager.ViewFactory.DisplayError(errorMsg, "Export Error");
                    }
                    else
                    {
                        ViewManager.ViewFactory.DisplayMessage("Export completed successfully", "Export Results");
                        result = true;
                    }
                }
                else
                {
                    ViewManager.ViewFactory.DisplayError("No data to export!", "Export Error");
                }
            }

            return result;
        }

        /// <summary>
        /// Validate the data entered into the Export Results view
        /// </summary>
        /// <returns>An error message if there are any problems, otherwise string.empty</returns>
        private string Validate()
        {
            // Assume all is valid
            string result = string.Empty;

            // Do we have a file to export to
            if (string.IsNullOrEmpty(View.ExportFile))
            {
                result = "You need to enter an file to export the data to";
            }

            // Do we have any selected results
            if (View.AvailableDatabases.Count(x => x.Result.SelectedForExport) <= 0)
            {
                result = string.Format("{0}\n{1}", result, "You need to select at least one result set to export");
            }

            return result;
        }
    }
}
